import { Map, MouseTool, CircleEditor } from 'react-amap';
import { toLnglat } from 'react-amap/lib/utils/common';
import { Link } from 'dva/router';
import { connect } from 'dva';
import React, { Component, Fragment } from 'react';
import { Card, Button, Modal, Select, Radio, Form, Input, Table, Divider, message } from 'antd';
import styles from './GeoLib.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Geolocation from '../../components/GDMap/Geolocation';
import EditTable from '../../components/EditTable';
import Autocomplete from '../../components/GDMap/Autocomplete';
import MapForm from '../../components/UpLoadForm/MapForm';
import { isArray } from 'lodash';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { Option } = Select;

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleAdd,
    handleModalVisible,
    handleChange,
    cityList,
    shapeCodes,
    typeCodes,
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleModalVisible();

      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="添加角色"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="城市">
        {form.getFieldDecorator('cityId', {
          rules: [{ required: true, message: '请输入区域名称...' }],
        })(
          <Select style={{ width: '50%' }} onChange={handleChange}>
            {cityList
              ? cityList.map(item => (
                  <Option key="name" value={item.code}>
                    {item.name}
                  </Option>
                ))
              : null}
          </Select>
        )}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="区域名称">
        {form.getFieldDecorator('areaName', {
          rules: [{ required: true, message: '请输入区域名称...' }],
        })(<Input placeholder="请输入区域名称" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="区域形状">
        {form.getFieldDecorator('areaShape', {
          rules: [{ required: true, message: '请选择角色类型...' }],
        })(
          <Select style={{ width: '50%' }}>
            {shapeCodes
              ? shapeCodes.map(item => (
                  <Option key="code" value={item.code}>
                    {item.name}
                  </Option>
                ))
              : null}
          </Select>
        )}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="区域类型">
        {form.getFieldDecorator('areaType', {
          rules: [{ required: true, message: '请选择角色类型...' }],
        })(
          <Select style={{ width: '50%' }}>
            {typeCodes
              ? typeCodes.map(item => (
                  <Option key="code" value={item.code}>
                    {item.name}
                  </Option>
                ))
              : null}
          </Select>
        )}
      </FormItem>
    </Modal>
  );
});

@connect(({ areaInfo, monitor }) => ({
  areaInfo,
  monitor,
}))
class GeoLib extends Component {
  constructor(props) {
    super(props);
    const self = this;
    this.editor = [];
    this.clickpos = '';
    this.state = {
      position: { lng: 114.066264, lat: 22.553522 },
      what: '点击添加按钮开始编辑区域',
      numbers: 0,
      isdrawing: false,
      isedit: false,
      issubmit: false,
      modalVisible: false,
      areaProp: {},
      divInfo: {},
      clickpos: {},
      editItem: {},
    };
    this.mapEvents = {
      created: mapinst => {
        //console.log(mapinst);
        self.mapinst = mapinst;
        self.contextMenu = new window.AMap.ContextMenu();

        //右键放大
        self.contextMenu.addItem(
          '放大一级',
          function() {
            mapinst.zoomIn();
          },
          0
        );

        //右键缩小
        self.contextMenu.addItem(
          '缩小一级',
          function() {
            mapinst.zoomOut();
          },
          1
        );
        self.contextMenu.addItem(
          '设置圆形区域',
          e => {
            self.rightAddCirCle(e);
          },
          1
        );
        mapinst.on('rightclick', function(e) {
          self.setState({ clickpos: e.lnglat });
          self.contextMenu.open(mapinst, e.lnglat);
        });
      },
    };
    this.toolEvents = {
      created: tool => {
        //console.log(tool);
        self.tool = tool;
      },
      draw({ obj }) {
        let { divInfo } = self.state;
        const { areaShape } = divInfo;
        if (self.tool) {
          self.tool.close();
        }
        self.setState({
          what: '关闭了绘图工具',
          isdrawing: false,
        });
        // //console.log("new obj", self.mapinst.getAllOverlays());
        if (areaShape === 'circle') {
          let center = obj.getCenter().getLng() + ',' + obj.getCenter().getLat();
          let radius = obj.getRadius() / 1000;
          self.setState({ divInfo: { ...divInfo, center, radius } });
        } else {
          let pathArray = obj.getPath();
          let path = pathArray.map(item => item.lng + ',' + item.lat);
          let center = path.join(';');
          self.setState({ divInfo: { ...divInfo, center } });
        }

        self.setState({ numbers: self.mapinst.getAllOverlays().length });
        // self.mapinst.plugin(["AMap.PolyEditor"],function(){
        //     let polylineEditor = new self.mapinst.PolyEditor(self.mapinst,obj);
        //     polylineEditor.open();
        // });
      },
    };
  }
  check(itemArray, itemName) {
    if (Array.isArray(itemArray)) {
      let filterItem = itemArray.filter(item => item.name === itemName);
      if (filterItem && filterItem.length > 0) {
        return filterItem[0].code;
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'areaInfo/fetch',
    });
    dispatch({
      type: 'areaInfo/fetchType',
    });
    dispatch({
      type: 'areaInfo/fetchShape',
    });
    dispatch({
      type: 'monitor/fetchCity',
      payload: {},
      callback: cityarray => {
        this.handleChange(cityarray[0].name);
      },
    });
  }

  updateDiv = value => {
    const { divInfo } = this.state;
    let NewDiv = { ...divInfo, ...value };
    this.setState({ divInfo: NewDiv });
  };
  handleChange = value => {
    console.log('city value', value);
    // const { monitor } = this.props;
    // let { cityList } = monitor;
    // const city = cityList.find(item => item.code === value);
    // if (city != null) {
    //   const { name, lngLat } = city;
    //   const longitude = lngLat.split(';')[0];
    //   const latitude = lngLat.split(';')[1];
    //   this.setState({
    //     city: name,
    //     position: {
    //       longitude,
    //       latitude,
    //     },
    //     isClick: false,
    //   });
    // }
  };
  drawPolygon = fieldsValue => {
    if (this.state.isedit) {
      Modal.info({
        title: '提示',
        content: (
          <div>
            <p>正在编辑，请编辑完成后再添加新的区域</p>
          </div>
        ),
      });
    } else if (this.tool) {
      console.log('drawpolygon', fieldsValue);
      const { areaShape } = fieldsValue;
      if (areaShape === 'circle') {
        this.tool.circle();
        this.setState({
          what: '准备绘制，双击鼠标结束',
          isdrawing: true,
          divInfo: { ...fieldsValue },
        });
      } else {
        this.tool.polygon();
        this.setState({
          what: '准备绘制，双击鼠标结束',
          isdrawing: true,
          divInfo: { ...fieldsValue },
        });
      }
    }
  };
  rightAddCirCle = e => {
    this.refs.mapform.validateFields((err, fieldsValue) => {
      if (err) return;
      const { radius, shape } = fieldsValue;
      const center = this.state.clickpos;
      let option = {
        radius: radius * 1000,
        center,
        strokeColor: '#F33', //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: '#ee2200', //填充颜色
        fillOpacity: 0.35, //填充透明度
      };
      this.setState({
        divInfo: { ...fieldsValue },
      });
      let circles = this.mapinst.getAllOverlays('circle');
      this.mapinst.remove(circles);
      this.drawCirCle(option, '圆');
    });
  };
  drawCirCle = (option, shape) => {
    if (shape === '圆') {
      const circle = new AMap.Circle(option);

      this.mapinst.add(circle);
    } else {
      const circle = new AMap.Polygon(option);

      this.mapinst.add(circle);
    }
    //this.tool.polygon();
  };
  // close() {
  //   if (this.tool) {
  //     this.tool.close();
  //   }
  //   this.setState({
  //     what: "关闭了鼠标工具"
  //   });
  // }
  clear = () => {
    if (this.mapinst) {
      Modal.confirm({
        title: '您确认要删除所区域么?',
        content: '点击确认将会删除掉所有的已设置区域',
        onOk: () => {
          this.mapinst.clearMap();
          this.setState({ numbers: 0 });
        },
        onCancel() {},
      });
    }
  };
  submit = () => {
    if (this.state.isAdd || this.state.isEdit) {
      message.error('正在添加或编辑，请关闭当前添加或编辑后重新点击');
    } else {
      // this.props.history.push('/matter/matterlib');
      this.mapinst.clearMap();
      this.setState({ modalVisible: true, isAdd: true });
    }
  };

  add = () => {
    const { dispatch } = this.props;
    const { clickpos } = this.state;
    this.refs.mapform.validateFields((err, fieldsValue) => {
      if (err) return;
      if (clickpos && JSON.stringify(clickpos) != '{}') {
        //有设置圆心
        const { radius, areaShape, areaName, areaType, areaId, cityId, center } = fieldsValue;

        let postvalue = {};
        postvalue = {
          cityId,
          areaName,
          areaType,
          areaPos: { posShape: areaShape, radius },
        };
        postvalue.areaPos.lngLat = clickpos.getLng() + ',' + clickpos.getLat();
        dispatch({
          type: 'areaInfo/add',
          payload: postvalue,
          callback: () => {
            this.handleModalVisible(false);
            this.setState({ clickpos: {}, isAdd: false });
            message.success('添加区域成功！');
            dispatch({
              type: 'areaInfo/fetch',
            });
          },
        });
      } else {
        message.error('请先右键选择设置圆形区域');
      }
    });
  };
  submitEdit = () => {
    const { isEditor } = this.state;
    if (isEditor) {
      message.error('请先关闭图形编辑器');
    } else {
      const { dispatch } = this.props;
      this.refs.mapform.validateFields((err, fieldsValue) => {
        if (err) return;

        const { radius, areaShape, areaName, areaType, areaId, cityId, center } = fieldsValue;
        let postvalue = {};
        postvalue = {
          areaId,
          cityId,
          areaName,
          areaType,
          areaPos: { posShape: areaShape, radius },
        };
        //let radius = areaProp.getRadius();
        //let center = areaProp.getCenter();
        //postvalue.areaPos.radius = radius / 1000;
        postvalue.areaPos.lngLat = center.getLng() + ',' + center.getLat();
        console.log('postvalue', postvalue);
        dispatch({
          type: 'areaInfo/edit',
          payload: postvalue,
          callback: () => {
            this.handleModalVisible(false);
            this.setState({ isEdit: false, isEditor: false });
            message.success('编辑区域成功！');
            dispatch({
              type: 'areaInfo/fetch',
            });
          },
        });
      });
    }
  };

  edit = () => {
    if (this.state.isdrawing) {
      Modal.info({
        title: '提示',
        content: (
          <div>
            <p>正在绘制，请绘制完成后再编辑</p>
          </div>
        ),
      });
    } else if (this.state.isedit) {
      this.editor.map(poly => poly.close());
      this.editor = [];
      //this.mapinst.getAllOverlays('polygon').map(poly => //console.log('path', poly.getPath()));
      this.setState({ isedit: false });
    } else {
      this.setState({ isedit: true });
      this.mapinst.getAllOverlays('polygon').map(item => {
        this.mapinst.plugin(['AMap.PolyEditor'], () => {
          const polylineEditor = new window.AMap.PolyEditor(
            this.mapinst,
            item // 获取第一个多边形
          );
          this.editor.push(polylineEditor);
        });
      });
      this.editor.map(poly => poly.open());
    }
  };

  handleModalVisible = (flag, isEditStatus = false) => {
    this.setState({ modalVisible: flag, isEdit: isEditStatus });
    if (flag === false) {
      if (this.editor && !isArray(this.editor)) {
        this.closeEditor();
      }
      this.setState({ isAdd: false, isEdit: false });
    }
  };
  closeeditor = () => {
    this.editor.map(poly => poly.close());

    //this.mapinst.getAllOverlays('polygon').map(poly => //console.log('path', poly.getPath()));
    this.setState({ isedit: false });
  };
  show = () => {
    const path = this.mapinst.getAllOverlays('polygon').map(poly => poly.getPath());
    alert('path', path);
  };
  renderDiv = () => {
    const { divInfo } = this.state;
    console.log('divInfo', divInfo);
    if (divInfo) {
      const { areaName, areaType, areaShape, center, radius } = divInfo;
      return (
        <div className={styles.layerStyle}>
          <p>区域名称：{areaName}</p>
          <p>区域类型：{areaType}</p>
          <p>区域形状：{areaShape}</p>
          <p>中心：{center}</p>
          <p>半径：{radius}</p>
        </div>
      );
    }
  };

  renderInput = () => {
    return (
      <div className="info">
        <div className="input-item">
          <div className="input-item-prepend">
            <span className="input-item-text" style="width:10rem;">
              区域名称
            </span>
            <span className="input-item-text" style="width:10rem;">
              区域半径
            </span>
          </div>
        </div>
      </div>
    );
  };

  selectfunc = e => {
    console.log('e', e);
    if (e.poi.location) {
      this.setState({ position: { longitude: e.poi.location.lng, latitude: e.poi.location.lat } });
    }
  };

  delArea = item => {
    Modal.confirm({
      title: '确认删除',
      content: '确认要删除此区域吗？删除后不可恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;

        dispatch({
          type: 'areaInfo/remove',
          payload: {
            areaId: item.areaId,
          },
          callback: () => {
            message.success('删除区域成功');
          },
        });
      },
    });
  };
  editSelectArea = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (this.state.isAdd || this.state.isEdit) {
      message.error('正在添加或编辑，请关闭当前添加或编辑后重新点击');
    } else if (selectedRows && selectedRows.length === 1) {
      this.editArea(selectedRows[0]);
    } else {
      message.error('每次只能编辑一个区域，请勾选后再点击');
    }
  };
  openEditor = () => {
    if (this.editor) {
      this.editor.open();
    }
  };
  closeEditor = () => {
    this.editor.close();
    this.setState({ isEditor: false });
  };
  editArea = item => {
    const { isEdit } = this.state;
    if (isEdit) {
      message.error('有其他区域正在编辑,请关闭后再编辑');
    } else {
      this.setState({ isEditor: true });
      this.handleModalVisible(true, true);
      const { shapeCodes, typeCodes } = this.props.areaInfo;
      const { cityList } = this.props.monitor;
      const { radius } = item.areaPos;
      let targetCircle = this.mapinst
        .getAllOverlays('circle')
        .filter(circle => circle.getExtData() === item.areaId);
      //this.setState({ isedit: true });
      console.log('edititem', item);
      this.mapinst.plugin(['AMap.CircleEditor'], () => {
        this.editor = new window.AMap.CircleEditor(
          this.mapinst,
          targetCircle[0] // 获取第一个多边形
        );
        this.editor.on('move', function(event) {
          console.log('触发事件：move');
        });

        this.editor.on('adjust', function(event) {
          console.log('触发事件：adjust');
        });

        this.editor.on('end', event => {
          console.log('触发事件： end');
          // event.target 即为编辑后的圆形对象
          this.refs.mapform.setFieldsValue({
            radius: event.target.getRadius() / 1000,
            center: event.target.getCenter(),
          });
        });
        this.editor.open();
      });
      //var circleEditor = new AMap.CircleEditor(this.mapinst, item);
      this.refs.mapform.setFieldsValue({
        areaId: item.areaId,
        areaShape: item.areaShapeId,
        areaName: item.areaName,
        cityId: item.cityId,
        areaType: item.areaTypeId,
        radius: radius,
      });
    }

    //this.editor.map(poly => poly.open());
  };
  onSelectChange = (selectedRowKeys, selectedRows) => {
    console.log('selectedRowKeys changed: ', selectedRows);
    this.setState({ selectedRowKeys, selectedRows });
    this.mapinst.clearMap();
    if (selectedRows.length > 0) {
      selectedRows.map(item => this.drawItem(item));
      let tail = selectedRows[selectedRows.length - 1];
      let { areaName, areaType, areaShape, areaPos } = tail;
      let lngLat = areaPos.lngLat.split(',');
      this.setState({
        position: {
          longitude: parseFloat(lngLat[0]),
          latitude: parseFloat(lngLat[1]),
        },
      });
    }
  };
  drawItem = item => {
    let { areaName, areaType, areaShape, areaPos } = item;
    if (areaShape === '圆') {
      let lngLat = areaPos.lngLat.split(',');
      let center = toLnglat({ lng: lngLat[0], lat: lngLat[1] });
      let option = {
        radius: areaPos.radius * 1000,
        center,
        strokeColor: '#37a2da', //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: '#1791fc', //填充颜色
        fillOpacity: 0.35, //填充透明度
        extData: item.areaId,
      };
      this.drawCirCle(option, areaShape);
    } else {
      let lngLat = areaPos.lngLat;
      let centerArray = lngLat.split(';');
      let pathArray = centerArray.map(item => {
        return toLnglat({ lng: item.split(',')[0], lat: item.split(',')[1] });
      });
      let option = {
        path: pathArray,
        strokeColor: '#F33', //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: '#ee2200', //填充颜色
        fillOpacity: 0.35, //填充透明度
      };

      this.drawCirCle(option, areaShape);
    }
  };
  // onSelectChange = (selectedRowKeys, selectedRows) => {
  //   console.log('onselect', selectedRowKeys, selectedRows);
  //   const selectRow = selectedRows[0];
  //   let { areaName, areaType, areaShape, areaPos } = selectRow;
  //   if (areaShape === '圆') {
  //     let lngLat = selectRow.areaPos.lngLat.split(',');
  //     this.setState({ position: { lng: parseFloat(lngLat[0]), lat: parseFloat(lngLat[1]) } });
  //     let center = toLnglat({ lng: lngLat[0], lat: lngLat[1] });
  //     let option = {
  //       radius: selectRow.areaPos.radius * 1000,
  //       center,
  //       strokeColor: '#F33', //线颜色
  //       strokeOpacity: 1, //线透明度
  //       strokeWeight: 3, //线粗细度
  //       fillColor: '#ee2200', //填充颜色
  //       fillOpacity: 0.35, //填充透明度
  //     };

  //     let divInfo = {
  //       areaName,
  //       areaType,
  //       areaShape,
  //       center: areaPos.lngLat,
  //       radius: areaPos.radius,
  //     };
  //     this.setState({ divInfo });
  //     this.drawCirCle(option, areaShape);
  //   } else {
  //     let lngLat = selectRow.areaPos.lngLat;
  //     let centerArray = lngLat.split(';');
  //     let pathArray = centerArray.map(item => {
  //       return toLnglat({ lng: item.split(',')[0], lat: item.split(',')[1] });
  //     });
  //     let option = {
  //       path: pathArray,

  //       strokeColor: '#F33', //线颜色
  //       strokeOpacity: 1, //线透明度
  //       strokeWeight: 3, //线粗细度
  //       fillColor: '#ee2200', //填充颜色
  //       fillOpacity: 0.35, //填充透明度
  //     };

  //     let divInfo = {
  //       areaName,
  //       areaType,
  //       areaShape,
  //       center: lngLat,
  //       radius: areaPos.radius,
  //     };
  //     this.setState({ divInfo });
  //     this.drawCirCle(option, areaShape);
  //   }
  // };
  setClickPos = value => {
    this.setState({ clickpos: value });
  };
  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const columns = [
      {
        title: '区域名称',
        dataIndex: 'areaName',
        editable: true,
      },
      {
        title: '区域类型',
        dataIndex: 'areaType',
      },

      {
        title: '区域形状',
        dataIndex: 'areaShape',
      },

      {
        title: '描述',
        dataIndex: 'shapeDescr',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '操作',
        width: 150,
        fixed: 'right',
        render: (text, record, index) => (
          <Fragment>
            <a onClick={() => this.delArea(record)}>删除</a>
          </Fragment>
        ),
      },
    ];
    const extraButton = (
      <div className={styles.extraContent}>
        <Button className={styles.buttonStyle} type="primary" onClick={this.submit}>
          增加区域
        </Button>
        <Button className={styles.buttonStyle} type="primary" onClick={this.editSelectArea}>
          编辑区域
        </Button>
        <Button className={styles.buttonStyle} type="primary" onClick={this.clear}>
          删除所有区域
        </Button>
      </div>
    );
    const pluginProps = {
      enableHighAccuracy: true,
      timeout: 10000,
      showButton: true,
    };
    const mapPlugins = ['Scale', 'OverView'];
    const style = { position: 'absolute', left: 5, top: 5 };
    return (
      <PageHeaderLayout>
        <Card
          xl={18}
          lg={24}
          md={24}
          sm={24}
          xs={24}
          className={styles.listCard}
          bordered={false}
          title="区域"
          style={{ marginTop: 24 }}
          bodyStyle={{ padding: '0 32px 40px 32px' }}
          extra={extraButton}
        >
          <div className={styles.mapChart}>
            <Map
              center={this.state.position}
              zoom="13"
              amapkey="74532947bf4c342a9f6e1546fe02325f"
              events={this.mapEvents}
              plugins={mapPlugins}
            >
              <Autocomplete
                options={{}}
                onSelect={e => this.selectfunc(e)}
                style={style}
                placeholder="地址查询"
                contextMenu={this.contextMenu}
                setClickPos={this.setClickPos}
              />
              <MouseTool events={this.toolEvents} />

              {/* <Button className={styles.button1Style}>Areas : {this.state.numbers}</Button> */}
              {/* <Geolocation {...pluginProps} /> */}
              <MapForm
                ref="mapform"
                contextMenu={this.contextMenu}
                handleAdd={this.drawPolygon}
                handleModalVisible={this.handleModalVisible}
                modalVisible={this.state.modalVisible}
                handleChange={this.handleChange}
                cityList={this.props.monitor.cityList}
                shapeCodes={this.props.areaInfo.shapeCodes}
                typeCodes={this.props.areaInfo.typeCodes}
                editItem={this.state.editItem}
                isEdit={this.state.isEdit}
                add={this.add}
                center={this.state.center}
                openEditor={this.openEditor}
                closeEditor={this.closeEditor}
                submitEdit={this.submitEdit}
              />
            </Map>
          </div>
          <div>
            <Table
              rowKey={row => row.areaId}
              selections={false}
              rowSelection={rowSelection}
              dataSource={this.props.areaInfo.list}
              columns={columns}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}

export default GeoLib;
